﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace AutoUpdate.util
{
    class DownLoadUtil
    {
        public static long totalBytes = 0;

        public static string FormatFileSizeDescription(int bytes)
        {
            if (bytes > 1024 * 1024)
                return string.Format("{0}M", Math.Round((double)bytes / (1024 * 1024), 2, MidpointRounding.AwayFromZero));
            if (bytes > 1024)
                return string.Format("{0}K", Math.Round((double)bytes / 1024, 2, MidpointRounding.AwayFromZero));
            return string.Format("{0}B", bytes);
        }

        public static bool DownloadFile(string localFolder, string remoteFolder, string fileName)
        {
            string url = remoteFolder + "/" + fileName;
            string path = localFolder + "/" + fileName;
            string dir = Path.GetDirectoryName(path);

            try
            {
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }

                WebRequest req = WebRequest.Create(url);
                WebResponse res = req.GetResponse();

                if (res.ContentLength == 0)
                {
                    return false;
                }

                //下载返回流
                Stream responseStream = res.GetResponseStream();

                //创建本地文件写入流
                Stream sw = new System.IO.FileStream(path, FileMode.OpenOrCreate);

                //定义缓冲区
                byte[] by = new byte[1024];

                //第一次读
                int osize = responseStream.Read(by, 0, by.Length);
                while (osize > 0)
                {
                    totalBytes += osize;
                    sw.Write(by, 0, osize);
                    osize = responseStream.Read(by, 0, by.Length);
                }

                //关闭流
                sw.Close();
                responseStream.Close();

                return true;
            }
            catch
            {
                return false;
            }
        }
    }
}

